package com.tracemap.websender.jsonparser;


import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class EmployeeJSON {
    public long Id;
    public long DeptId;
    public long SalaryGradeId;
    public String FirstName;
    public String LastName;
    public String Email;
    public String Phone;
    public String Title;
    public boolean TakesLongLunches;

    public EmployeeJSON() {
    }

    public EmployeeJSON(JSONObject obj) throws JSONException {
        deserializeFromObj(obj);
    }

    public EmployeeJSON(String serializedObj) throws JSONException {
        deserialize(serializedObj);
    }

    public void deserialize(String serializedObj) throws JSONException {
        JSONObject obj = new JSONObject(serializedObj);
        deserializeFromObj(obj);
    }

    public void deserializeFromObj(JSONObject obj) throws JSONException {
        this.Id = obj.getLong("Id");
        this.DeptId = obj.getLong("DeptId");
        this.SalaryGradeId = obj.getLong("SalaryGradeId");
        this.FirstName = obj.getString("FirstName");
        this.LastName = obj.getString("LastName");
        this.Email = obj.getString("Email");
        this.Phone = obj.getString("Phone");
        this.Title = obj.getString("Title");
        this.TakesLongLunches = Boolean.parseBoolean(obj.getString("TakesLongLunches"));
    }

    public String serialize() throws JSONException {
        return serializeToObj().toString();
    }

    public JSONObject serializeToObj() throws JSONException {
        JSONObject serializedObj = new JSONObject();
        serializedObj.put("Id", this.Id);
        serializedObj.put("DeptId", this.DeptId);
        serializedObj.put("SalaryGradeId", this.SalaryGradeId);
        serializedObj.put("FirstName", this.FirstName);
        serializedObj.put("LastName", this.LastName);
        serializedObj.put("Email", this.Email);
        serializedObj.put("Phone", this.Phone);
        serializedObj.put("Title", this.Title);
        serializedObj.put("TakesLongLunches", this.TakesLongLunches);

        return serializedObj;
    }

    public static ArrayList<EmployeeJSON> deserializeArray(String serializedArray) throws JSONException {
        JSONArray jsonObjs = new JSONArray(serializedArray);
        ArrayList<EmployeeJSON> employees = new ArrayList<EmployeeJSON>();
        for (int i=0; i<jsonObjs.length(); i++) {
            JSONObject employee = jsonObjs.getJSONObject(i);
            employees.add(new EmployeeJSON(employee));
        }

        return employees;
    }
}
